<template>
  <div class="auth-page">
    <!-- Three.js Canvas -->
    <canvas ref="threeCanvas" class="three-canvas"></canvas>
    
    <!-- Auth Container -->
    <div class="auth-container">
      <div class="auth-card glass">
        <div class="auth-header">
          <h2 class="auth-title">{{ isLogin ? '登录' : '注册' }}</h2>
          <p class="auth-subtitle">{{ isLogin ? '欢迎回到音乐世界' : '加入我们的音乐之旅' }}</p>
        </div>
        
        <!-- Login Form -->
        <form v-if="isLogin" @submit.prevent="handleLogin" class="auth-form">
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-user"></i>
              用户名
            </label>
            <input 
              v-model="loginForm.username" 
              type="text" 
              class="form-control glass-input"
              placeholder="请输入用户名"
              required
            >
          </div>
          
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-lock"></i>
              密码
            </label>
            <input 
              v-model="loginForm.password" 
              type="password" 
              class="form-control glass-input"
              placeholder="请输入密码"
              required
            >
          </div>
          
          <button type="submit" class="btn btn-primary auth-btn">
            <i class="fas fa-sign-in-alt me-2"></i>
            登录
          </button>
        </form>
        
        <!-- Register Form -->
        <form v-else @submit.prevent="handleRegister" class="auth-form">
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-user"></i>
              用户名
            </label>
            <input 
              v-model="registerForm.username" 
              type="text" 
              class="form-control glass-input"
              placeholder="请输入用户名（至少3个字符）"
              required
              minlength="3"
            >
          </div>
          
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-envelope"></i>
              邮箱
            </label>
            <input 
              v-model="registerForm.email" 
              type="email" 
              class="form-control glass-input"
              placeholder="请输入邮箱地址"
              required
            >
          </div>
          
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-lock"></i>
              密码
            </label>
            <input 
              v-model="registerForm.password" 
              type="password" 
              class="form-control glass-input"
              placeholder="请输入密码（至少6个字符）"
              required
              minlength="6"
            >
          </div>
          
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-lock"></i>
              确认密码
            </label>
            <input 
              v-model="registerForm.confirmPassword" 
              type="password" 
              class="form-control glass-input"
              placeholder="请再次输入密码"
              required
            >
          </div>
          
          <button type="submit" class="btn btn-primary auth-btn">
            <i class="fas fa-user-plus me-2"></i>
            注册
          </button>
        </form>
        
        <!-- Toggle Button -->
        <div class="auth-toggle">
          <p v-if="isLogin">
            还没有账户？ 
            <button @click="isLogin = false" class="toggle-btn">立即注册</button>
          </p>
          <p v-else>
            已有账户？ 
            <button @click="isLogin = true" class="toggle-btn">立即登录</button>
          </p>
        </div>
        
        <!-- Success Message -->
        <div v-if="successMessage" class="success-message">
          <i class="fas fa-check-circle"></i>
          {{ successMessage }}
        </div>
        
        <!-- Error Message -->
        <div v-if="errorMessage" class="error-message">
          <i class="fas fa-exclamation-circle"></i>
          {{ errorMessage }}
        </div>
      </div>
    </div>
    
    <!-- Floating Elements -->
    <div class="floating-elements">
      <div class="floating-note note-1">♪</div>
      <div class="floating-note note-2">♫</div>
      <div class="floating-note note-3">♪</div>
      <div class="floating-note note-4">♫</div>
      <div class="floating-note note-5">♪</div>
    </div>
  </div>
</template>

<script>
import * as THREE from 'three'

export default {
  name: 'Auth',
  data() {
    return {
      isLogin: true,
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      successMessage: '',
      errorMessage: ''
    }
  },
  mounted() {
    // 初始化Three.js对象（不在data中，避免响应式冲突）
    this.scene = null
    this.camera = null
    this.renderer = null
    this.particles = null
    this.animationId = null
    
    // 延迟初始化，确保DOM完全加载
    this.$nextTick(() => {
      this.initThreeJS()
      this.animate()
    })
    
    window.addEventListener('resize', this.onWindowResize)
  },
  beforeUnmount() {
    if (this.animationId) {
      cancelAnimationFrame(this.animationId)
    }
    window.removeEventListener('resize', this.onWindowResize)
    if (this.renderer) {
      this.renderer.dispose()
    }
  },
  methods: {
    initThreeJS() {
      try {
        // 检查canvas是否存在
        if (!this.$refs.threeCanvas) {
          console.warn('Canvas element not found')
          return
        }

        // Scene
        this.scene = new THREE.Scene()
        
        // Camera
        this.camera = new THREE.PerspectiveCamera(
          75, 
          window.innerWidth / window.innerHeight, 
          0.1, 
          1000
        )
        this.camera.position.z = 50
        
        // Renderer
        this.renderer = new THREE.WebGLRenderer({ 
          canvas: this.$refs.threeCanvas,
          alpha: true,
          antialias: true
        })
        this.renderer.setSize(window.innerWidth, window.innerHeight)
        this.renderer.setClearColor(0x000000, 0)
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
        
        // Create particles
        this.createParticles()
        
        // Add lighting
        const ambientLight = new THREE.AmbientLight(0x404040, 0.5)
        this.scene.add(ambientLight)
        
        const pointLight = new THREE.PointLight(0xff6b6b, 1, 100)
        pointLight.position.set(10, 10, 10)
        this.scene.add(pointLight)
        
        const pointLight2 = new THREE.PointLight(0x4ecdc4, 1, 100)
        pointLight2.position.set(-10, -10, 10)
        this.scene.add(pointLight2)
        
        console.log('Three.js initialized successfully')
      } catch (error) {
        console.error('Failed to initialize Three.js:', error)
      }
    },
    
    createParticles() {
      const geometry = new THREE.BufferGeometry()
      const count = 5000
      
      const positions = new Float32Array(count * 3)
      const colors = new Float32Array(count * 3)
      
      const color1 = new THREE.Color(0xff6b6b)
      const color2 = new THREE.Color(0x4ecdc4)
      const color3 = new THREE.Color(0xffd93d)
      
      for (let i = 0; i < count; i++) {
        const i3 = i * 3
        
        // Positions
        positions[i3] = (Math.random() - 0.5) * 200
        positions[i3 + 1] = (Math.random() - 0.5) * 200
        positions[i3 + 2] = (Math.random() - 0.5) * 200
        
        // Colors
        const randomColor = Math.random()
        let selectedColor
        if (randomColor < 0.33) {
          selectedColor = color1
        } else if (randomColor < 0.66) {
          selectedColor = color2
        } else {
          selectedColor = color3
        }
        
        colors[i3] = selectedColor.r
        colors[i3 + 1] = selectedColor.g
        colors[i3 + 2] = selectedColor.b
      }
      
      geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))
      geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3))
      
      const material = new THREE.PointsMaterial({
        size: 2,
        vertexColors: true,
        transparent: true,
        opacity: 0.8
      })
      
      this.particles = new THREE.Points(geometry, material)
      this.scene.add(this.particles)
    },
    
    animate() {
      // 检查所有必需的对象是否已初始化
      if (!this.renderer || !this.scene || !this.camera) {
        return
      }
      
      this.animationId = requestAnimationFrame(this.animate)
      
      try {
        // Rotate particles
        if (this.particles) {
          this.particles.rotation.x += 0.001
          this.particles.rotation.y += 0.002
        }
        
        this.renderer.render(this.scene, this.camera)
      } catch (error) {
        console.error('Animation error:', error)
        // 停止动画循环以防止错误重复
        if (this.animationId) {
          cancelAnimationFrame(this.animationId)
          this.animationId = null
        }
      }
    },
    
    onWindowResize() {
      if (!this.camera || !this.renderer) {
        return
      }
      
      this.camera.aspect = window.innerWidth / window.innerHeight
      this.camera.updateProjectionMatrix()
      this.renderer.setSize(window.innerWidth, window.innerHeight)
    },
    
    handleLogin() {
      this.clearMessages()
      
      const { username, password } = this.loginForm
      
      if (!username || !password) {
        this.errorMessage = '请填写所有字段'
        return
      }
      
      // 从本地存储获取用户信息
      const users = JSON.parse(localStorage.getItem('musicUsers') || '[]')
      const user = users.find(u => u.username === username && u.password === password)
      
      if (user) {
        this.successMessage = '登录成功！正在跳转...'
        // 保存当前登录用户
        localStorage.setItem('currentUser', JSON.stringify(user))
        // 延迟跳转到首页
        setTimeout(() => {
          this.$router.push('/')
        }, 1500)
      } else {
        this.errorMessage = '用户名或密码错误'
      }
    },
    
    handleRegister() {
      this.clearMessages()
      
      const { username, email, password, confirmPassword } = this.registerForm
      
      if (!username || !email || !password || !confirmPassword) {
        this.errorMessage = '请填写所有字段'
        return
      }
      
      if (password !== confirmPassword) {
        this.errorMessage = '两次输入的密码不一致'
        return
      }
      
      if (password.length < 6) {
        this.errorMessage = '密码长度至少6个字符'
        return
      }
      
      if (username.length < 3) {
        this.errorMessage = '用户名长度至少3个字符'
        return
      }
      
      // 检查邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(email)) {
        this.errorMessage = '请输入有效的邮箱地址'
        return
      }
      
      // 从本地存储获取现有用户
      const users = JSON.parse(localStorage.getItem('musicUsers') || '[]')
      
      // 检查用户名是否已存在
      if (users.find(u => u.username === username)) {
        this.errorMessage = '用户名已存在'
        return
      }
      
      // 检查邮箱是否已存在
      if (users.find(u => u.email === email)) {
        this.errorMessage = '邮箱已被注册'
        return
      }
      
      // 创建新用户
      const newUser = {
        id: Date.now(),
        username,
        email,
        password,
        registerDate: new Date().toISOString()
      }
      
      users.push(newUser)
      localStorage.setItem('musicUsers', JSON.stringify(users))
      
      this.successMessage = '注册成功！请登录'
      
      // 清空表单并切换到登录
      this.registerForm = {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
      
      setTimeout(() => {
        this.isLogin = true
        this.clearMessages()
      }, 2000)
    },
    
    clearMessages() {
      this.successMessage = ''
      this.errorMessage = ''
    }
  }
}
</script>

<style scoped>
.auth-page {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.three-canvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.auth-container {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 450px;
  padding: 0 20px;
}

.auth-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 40px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 25px 45px rgba(0, 0, 0, 0.3);
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: white;
  margin-bottom: 10px;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.auth-subtitle {
  color: rgba(255, 255, 255, 0.8);
  font-size: 1rem;
  margin: 0;
}

.auth-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 25px;
}

.form-label {
  display: block;
  color: white;
  font-weight: 500;
  margin-bottom: 8px;
  font-size: 0.9rem;
}

.form-label i {
  margin-right: 8px;
  color: #4ecdc4;
}

.glass-input {
  width: 100%;
  padding: 15px 20px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 10px;
  color: white;
  font-size: 1rem;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.glass-input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.glass-input:focus {
  outline: none;
  border-color: #4ecdc4;
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 0 20px rgba(78, 205, 196, 0.3);
}

.auth-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  border: none;
  border-radius: 10px;
  color: white;
  font-size: 1.1rem;
  font-weight: 600;
  transition: all 0.3s ease;
  cursor: pointer;
}

.auth-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}

.auth-toggle {
  text-align: center;
  margin-top: 25px;
}

.auth-toggle p {
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.toggle-btn {
  background: none;
  border: none;
  color: #4ecdc4;
  text-decoration: underline;
  cursor: pointer;
  font-weight: 500;
  transition: color 0.3s ease;
}

.toggle-btn:hover {
  color: #ff6b6b;
}

.success-message,
.error-message {
  padding: 15px;
  border-radius: 10px;
  margin-top: 20px;
  text-align: center;
  font-weight: 500;
}

.success-message {
  background: rgba(46, 204, 113, 0.2);
  color: #2ecc71;
  border: 1px solid rgba(46, 204, 113, 0.3);
}

.error-message {
  background: rgba(231, 76, 60, 0.2);
  color: #e74c3c;
  border: 1px solid rgba(231, 76, 60, 0.3);
}

.success-message i,
.error-message i {
  margin-right: 8px;
}

/* Floating Elements */
.floating-elements {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.floating-note {
  position: absolute;
  font-size: 2rem;
  color: rgba(255, 255, 255, 0.3);
  animation: float 6s ease-in-out infinite;
}

.note-1 {
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.note-2 {
  top: 20%;
  right: 15%;
  animation-delay: 1.2s;
}

.note-3 {
  bottom: 30%;
  left: 20%;
  animation-delay: 2.4s;
}

.note-4 {
  bottom: 15%;
  right: 25%;
  animation-delay: 3.6s;
}

.note-5 {
  top: 60%;
  left: 50%;
  animation-delay: 4.8s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.3;
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
    opacity: 0.6;
  }
}

/* Responsive */
@media (max-width: 768px) {
  .auth-card {
    padding: 30px 25px;
    margin: 20px;
  }
  
  .auth-title {
    font-size: 2rem;
  }
  
  .floating-note {
    font-size: 1.5rem;
  }
}

@media (max-width: 480px) {
  .auth-card {
    padding: 25px 20px;
  }
  
  .auth-title {
    font-size: 1.8rem;
  }
}
</style>
